<?php
namespace Home\Controller;
use Think\Controller;
class ShopcarController extends PublicController {
    public function cart(){
		//拦截加入购物车没有登录的时候
		$name = session('name');
		if(empty($name)){
			$this->redirect("Public/login");
		}
		
		$this->assign("k",CONTROLLER_NAME);
		$this->assign("f",ACTION_NAME);
		$this->shop();
		$this->calculate();
		$this->display();
	}
	
	//购物车商品输出
	public function shop(){
		$user_name =  session('name');
		$data['user'] = $user_name;
		//用户id
		$user_ids = M('user')->field("id")->where("name = '$user_name'")->find();
		$user_id = $user_ids['id'];
		$res = M('shoping')->where("user_id = '$user_id' and status = '1'")->select();
		
		$this->assign("res",$res);
		//var_dump($res);
		/* foreach($res as $k=>$v){
			$price[] = $res[$k]['price']*$res[$k]['number'];
			$this->assign("price",$price);
			
		} */
		//var_dump($price);
		//var_dump($number);
		
	}
	//cart商品数量点击加1减1存到数据库
	public function addNum(){
		$this->calculate();
		$id = $_POST['id'];
		$number = $_POST['number'];
		// $allprice = $_POST['allprice'];

		$res = M('shoping')->where("p_id = $id")->find();
		
		$data['number']=$number;
		M('shoping')->where("p_id = $id")->save($data);
	}
	
	//删除购物车里的商品
	public function del(){
		$id = $_GET["uid"];
		$res = M('shoping')->where("p_id = $id")->delete();
		//var_dump($res);
		if($res){
			$this->redirect("Shopcar/cart");
		}
	}
	//计算总数量/价格
	public function calculate(){
		//session 用户名
		$user_name =  session('name');
		$data['user'] = $user_name;
		//用户id
		$user_ids = M('user')->field("id")->where("name = '$user_name'")->find();
		$user_id = $user_ids['id'];
		$info = M('shoping')->where("user_id = '$user_id' and status = '1'")->select();
		$totalcost = 0;
		$totalnum = 0;
		foreach($info as $k=>$v){
			
			$totalcost += $v['price'] * $v['number'];
			$totalnum += $v['number'];
		}
		$this->assign("totalcost",$totalcost);
		$this->assign("totalnum",$totalnum);
		//var_dump($totalnum);
	}
}